package com.foreknow.elmboot.service.impl;

import  com.foreknow.elmboot.mapper.OrderDetailetMapper;
import com.foreknow.elmboot.mapper.CartMapper;
import com.foreknow.elmboot.mapper.OrdersMapper;
import com.foreknow.elmboot.po.Cart;
import com.foreknow.elmboot.po.Orderdetailet;
import com.foreknow.elmboot.po.Orders;
import com.foreknow.elmboot.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OrdersServiceImpl  implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private OrderDetailetMapper orderDetailetMapper;


    @Override
    public int createOrders(Orders orders) {
        ordersMapper.createOrders(orders);          // 将新的订单存入
        String userId = orders.getUserId();         // 从订单中获得用户编号
        Integer businessId = orders.getBusinessId();    // 从订单中获得商家编号
        Integer ordersId = orders.getOrderId();         // 获得订单编号
        Cart cart = new Cart();
        cart.setUserId(userId);
        cart.setBusinessId(businessId);
        // 根据当前订单中的用户编号和商家编号获得购物车中的信息
        List<Cart> cartList = cartMapper.listCart(cart);
        for (Cart cart1 : cartList) {
            // 将购物车的信息存入订单详情
            Integer foodId = cart1.getFoodId();
            Integer quantity = cart1.getQuantity();
            Orderdetailet orderDetailet = new Orderdetailet();
            orderDetailet.setOrderId(ordersId);
            orderDetailet.setFoodId(foodId);
            orderDetailet.setQuantity(quantity);
            orderDetailetMapper.saveOrderDetailet(orderDetailet);
            // 删除购物车中已下单的信息
            cartMapper.removeCart(cart1.getUserId(),cart1.getBusinessId(),cart1.getFoodId());
        }
        return ordersId;                 // 返回新订单的编号
    }

    @Override
    public Orders getOrdersById(Integer orderId) {
        return ordersMapper.getOrdersById(orderId);
    }

    @Override
    public List<Orders> listOrdersByUserId(String userId) {
        return ordersMapper.listOrdersByUserId(userId);
    }


    @Override
    public int updateOrderByOrderId (Integer orderId){
        return ordersMapper.updateOrderByOrderId(orderId);
    }
}
